#include "pwm.h"
#include "led.h"

TIM_HandleTypeDef pwm_handle = {0};

void pwm_init(uint16_t arr, uint16_t psc)
{
    TIM_OC_InitTypeDef oc_config = {0};
    
    pwm_handle.Instance = TIM3;
    pwm_handle.Init.Prescaler = psc;
    pwm_handle.Init.Period = arr;
    pwm_handle.Init.CounterMode = TIM_COUNTERMODE_UP;
    pwm_handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
    
    oc_config.OCMode = TIM_OCMODE_PWM1;
    oc_config.Pulse = arr / 2;
    oc_config.OCPolarity = TIM_OCPOLARITY_LOW;
    
    HAL_TIM_PWM_Init(&pwm_handle);
    HAL_TIM_PWM_ConfigChannel(&pwm_handle,&oc_config,TIM_CHANNEL_3);
    HAL_TIM_PWM_Start(&pwm_handle, TIM_CHANNEL_3);
}

void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
{
    if (htim->Instance != TIM3)
        return ;
    
    __HAL_RCC_TIM3_CLK_ENABLE();
    led_init();
}

void pwm_pulse_set(uint16_t val)
{
    __HAL_TIM_SET_COMPARE(&pwm_handle,TIM_CHANNEL_3,val);
}

void TIM3_IRQHandler(void)
{
    HAL_TIM_IRQHandler(&pwm_handle);
}



